import { courseDetail } from "./api/index.js"
import { BtMessage } from './utils/BtMessage.js'

console.log("href", window.location.href)


$(document).ready(() => {
    const courseId = getUrlParam("id")
    if (!courseId) {
        BtMessage({
            type: 'error',
            message: "课程不存在"
        })
        setTimeout(() => {
            window.location.href = "/"
        }, 2000)
        return
    }

    courseDetail(courseId).then(res => {
        console.log("res", res)

        if (res.code != 200) {
            BtMessage({
                type: 'error',
                message: res.msg || '课程不存在'
            })
            return
        }
        const obj = res.data
        
        $("#c-d-img").attr("src", obj.img)
        $("#c-d-title").text(obj.name)
        $("#c-d-detail").text(obj.description)
        $("#course-profile").text(obj.profile).attr("title", obj.profile)

        $("#c-d-amount").text(obj.joinLearning)

        const totalTime = createChapter($("#c-d-list"), obj.courseList)
        $("#c-d-time").text(Math.floor(totalTime / 60) + "分钟")
        console.log("totalTime", totalTime)
        if (!totalTime) {
            $("#c-d-list-none").removeClass("d-none")
        }


        // 修改网站标题
        document.title = obj.name + " - 课程详情 | 桂北程序员 - IT培训"
    })
})

const getUrlParam = (name) => {

    const url = window.location.href
    const params = url.substring(url.indexOf("?") + 1).split("&")

    for (let item of params) {
        const arr = item.split("=")
        if (arr[0] == name) {
            return arr[1]
        }
    }
}



const createChapter = (target, data) => {
    let totalTime = 0
    if (!data) {
        return 0
    }
    data.forEach((chapter, index) => {
        let template = `
        <p class="text-muted mb-1 mt-3">章节${ index + 1 }：${ chapter.name }</p>
        <ul class="list-group list-group-flush">`

        if (chapter.list) {
            chapter.list.forEach((item, index2) => {
                template += `
                <li class="list-group-item list-group-item-action d-flex justify-content-between">
                    ${ (index + 1) + "." + (index2 + 1) + " " + item.name }
                    <div class="text-muted">
                        <i class="bi bi-camera-video"></i>
                        <span>${ String(item.time / 60).padStart(2, '0') + ":" + String(item.time % 60).padStart(2, '0') }</span>
                    </div>
                </li>`
    
                totalTime += item.time
            })

            target.append(template + "</ul>")
        }
        


        
        
    })

    return totalTime
};